package com.lanjiu.lib.communication.timer;

import com.lanjiu.pro.business.BusinessProtocolMessageStandard;
import com.lanjiu.lib.communication.interf.IMSClientInterface;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import io.netty.util.internal.StringUtil;

/**
 * @description:
 * @author: Panwei
 * @date: 2019/12/13 19:43
 */
public class RequestTimeoutTimerManager {

    private Map<String, RequestTimeoutTimer> mRequestTimeoutMap;
    private IMSClientInterface mImsClient;// ims客户端

    public RequestTimeoutTimerManager(IMSClientInterface imsClient) {
        this.mRequestTimeoutMap = new ConcurrentHashMap<>();
        this.mImsClient = imsClient;
    }

    /**
     * 添加请求消息到发送超时管理器
     *
     * @param msg
     */
    public void add(BusinessProtocolMessageStandard.CheckUnifiedEntranceMessage msg) {
        if (msg == null)
            return;
        BusinessProtocolMessageStandard.UnifiedEntranceMessage unifiedEntranceMessage = msg.getUnifiedEntranceMessage();
//        if (unifiedEntranceMessage.getDataType() == BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType.FriendChatProtocol
//                || unifiedEntranceMessage.getDataType() == BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType.GroupChatProtocol) {
//            // 如果是聊天消息类型，不加入请求超时管理器
//            return;
//        }
        String msgId = msg.getUnifiedEntranceMessage().getHead().getUniqueIdentify();
        if (!mRequestTimeoutMap.containsKey(msgId)) {
            RequestTimeoutTimer timer = new RequestTimeoutTimer(mImsClient, msg);
            mRequestTimeoutMap.put(msgId, timer);
        }
    }

    public void remove(String requestId) {
        if (StringUtil.isNullOrEmpty(requestId)) return;
        if (mRequestTimeoutMap.containsKey(requestId)) {
            RequestTimeoutTimer timer = mRequestTimeoutMap.get(requestId);
            if (timer != null) {
                timer.cancel();
                timer = null;
            }
            mRequestTimeoutMap.remove(requestId);
        }
    }

    public void clear() {
        if (mRequestTimeoutMap.size() > 0) {
            for (String requestId : mRequestTimeoutMap.keySet()) {
                remove(requestId);
            }
        }
    }
}
